package com.dfs.parent.gateway.handler;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.dfs.parent.common.core.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author dahong
 * @Date 2024/2/7 22:22
 */
@Slf4j
public class SentinelFallbackHandler implements BlockRequestHandler {


    @Override
    public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable e) {
        log.error("------------- trigger gateway sentinel rule route:{} -------------{}"
                ,serverWebExchange.getRequest().getURI().getPath(),e.fillInStackTrace());
        Result reuslt = null;
        if (e instanceof FlowException) {
            // 限流
            reuslt = Result.fail(5001,"接口限流");
        } else if (e instanceof DegradeException) {
            // 降级
            reuslt = Result.fail(5002,"服务降级");
        } else if (e instanceof ParamFlowException) {
            if(!e.getMessage().equals("$D")){
                // 发送黑名单
            }
            // 热点参数
            reuslt = Result.fail(5003,"热点参数限流",serverWebExchange.getRequest().getURI().getPath());
        } else if (e instanceof SystemBlockException) {
            // 系统保护
            reuslt = Result.fail(5004,"触发系统保护规则");
        } else if (e instanceof AuthorityException) {
            // 授权规则
            reuslt = Result.fail(5005,"授权规则不通过");
        }
//        Map<String, String> map = new HashMap<>();
//        map.put("code", String.valueOf(HttpStatus.TOO_MANY_REQUESTS.value()));
//        map.put("msg", HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
//        map.put("route", serverWebExchange.getRequest().getURI().getPath());


        return ServerResponse
                .status(HttpStatus.TOO_MANY_REQUESTS)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(reuslt));
    }
}
